/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package my.processmanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * 进程类
 * @author shaw
 */
public class MyProcess {
    
    private Process p = null;           //进程
    private String processState = new String("Down");   //进程运行状态
    private String name = new String("暂无"); //进程文件名称
    private String pid = null;  //pid
    private Date startTime;          //进程开始时间
    private String parm = new String("无");             //进程所执行的参数
    private String path = null; //进程文件所在的绝对路径
    private String result = null; //返回结果

    /**
     * 注意：在执行完getRunResult()之后才能执行
     * @return 进程名称
     */
    public String getName() {
        return this.name;
    }
    
    /**
     * 注意：在执行完getRunResult()之后才能执行
     * @return long:进程PID
     */
    public String getPID() {
        return this.pid;
    }

    /**
     * 注意：在执行完getRunResult()之后才能执行
     * @return 进程开始时间
     */
    public Date getStartTime() {
        return this.startTime;
    }
    
    /**
     * 注意：在执行完getRunResult()之后才能执行
     * @return 进程文件所在路径
     */
    public String getPath() {
        return this.path;
    }
    
    /**
     * 注意：在执行完getRunResult()之后才能执行
     * @return 执行jar包时所添加的参数
     */
    public String getParm() {
        return this.parm;
    }
    
    /**
     * 返回进程状态
     * @return true为存活
     */
    public String getProcessState() {
        return this.processState;
    }
    
    public String getResult() {
        return this.result;
    }
    
    public MyProcess() {
        
    }
    
    public MyProcess(String path1, String parm1){
        result = getRunResult(path1, parm1);
    }

    /**
     * 执行命令，并返回结果
     * @param path1:文件路径； parm1:参数
     * @return String：命令执行结果
     */
    public String getRunResult(String path1, String parm1) {
        String toRun = "java -jar " +  path1 + " " + parm1; //所要执行的命令
        String[] temp1 = toRun.split("\\\\");
        String[] temp2 = temp1[temp1.length-1].split(".jar");
        this.path = path1;                  //设置进程文件所在路径
        this.name = temp2[0];    //设置进程名称
        this.parm = parm1;                   //设置进程所用参数
        
        String result = new String();       //返回的结果
        try {
            p = Runtime.getRuntime().exec(toRun);   //执行命令
            p.getOutputStream().close(); // 关掉输入流
            result = "Input##";
            pid = setProcessPID(p);                 //记录进程PID
            startTime = new Date();                 //记录进程开始时间
            processState = "Running";                    //设置进程存活
            return result;
        } catch (IOException e) {
            System.err.println("Process为null");
            return "0##" + "无法建立新进程" + e;
        }
        /*InputStreamReader inputStreamReader1 = new InputStreamReader(p.getInputStream());   //获取进程正常输入流
        
        InputStreamReader errStreamReader2 = new InputStreamReader(p.getErrorStream());     //获取进程错误流
        try {
            BufferedReader brInput = new BufferedReader(inputStreamReader1);
            String str = new String();
            //result = "Input##";
            while ((str = (brInput.readLine())) != null) {
                result = result + str;
            }
        } catch (IOException e) {
            System.out.println("IOExcption: " + e);
            return "IOExcption##" + e;
        }
        try {
            BufferedReader brErr = new BufferedReader(errStreamReader2);
            String str = "";
            result = "Error##";
            while ((str = brErr.readLine()) != null) {
                result = result + str;
            }
        } catch (Exception e) {
        }*/
    }

    /**
     *
     * @param child
     * @return 进程PID
     */
    private String setProcessPID(Process child) {
        long pid = -1;
        Field field = null;
        try {
            field = child.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(child));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Long.toString(pid);
    }
    
    /**
     * 根据PID遍历系统进程表，来判断进程是否存活
     * 注意：在执行完getRunResult()之后才能执行
     * @return 活着true
     */
    public boolean isRun(){
        BufferedReader bufferedReader = null;
            String isRun = "tasklist -fi \"pid eq " + pid + "\"";
            try {
                Process p = Runtime.getRuntime().exec(isRun);
                bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(pid)) {
                    return true;
                }
            }
            this.processState = "Down";
            return false;
            } catch (IOException ex) {
                System.out.println("无法判断进程是否存活。"+ ex);
                return true;
            }
    }
    
    public void  shutdown() {
        if (!processState.equals("Running")) {
            System.err.println("错误：程序不是运行状态！");
            return ;
        }
        String shutCommend = "taskkill /PID "+ this.pid + " /T";
        //String shutCommend = "taskkill /PID "+ this.pid;
        try {
            Runtime.getRuntime().exec(shutCommend);
            this.processState = "Waiting";
        } catch (Exception e) {
            System.err.println("错误："+ e);
        }
    }
        
                
}
